package com.yang.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yang.dao.BaseDAO;
import com.yang.dao.PermissionDao;
import com.yang.dao.RoleDao;
import com.yang.entity.Permissions;
import com.yang.entity.Roles;
import com.yang.service.PermissionService;
import com.yang.utils.UserUtils;

@Service
public class PermissionServiceImpl implements PermissionService {

	@Autowired
	private PermissionDao permissionDao;
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private BaseDAO<Permissions> baseDao;
	
	@Override
	public List<Permissions> getPermissionTree(String rid) {
		
		//下面代码的作用是，勾选当前登录用户的对应的权限
		/*if(UserUtils.isAllPermission()==true){	//当前用户为超级管理员，具有ALL权限
		for (Permissions permission : permissions) {
			permission.setChecked(true);
		}
		}else{		//非超管，勾选对应的权限
			List<Permissions> loginUserPs = UserUtils.getLoginUserPermissons();
			for (Permissions loginP : loginUserPs) {
				for (Permissions allP : permissions) {
					if (loginP.getId().equals(allP.getId())) {
						allP.setChecked(true);
					}else{
						allP.setChecked(false);
					}
				}
			}
		}*/
		Roles role =  roleDao.findOne(rid);
		if(null!=role){
			List<Permissions> permissions =  permissionDao.getPermissionTree();
			if(UserUtils.isRoleHasAllPermisson(role)){			//当前角色具有ALL所有权限
				for (Permissions permission : permissions) {
					permission.setChecked(true);
				}
				return permissions;
			}else{	//不具有ALL权限
				Set<Permissions> nowRolePermissions =  role.getPermissions();
				for (Permissions allP : permissions) {
					if(nowRolePermissions.contains(allP)){
						allP.setChecked(true);
					}else{
						allP.setChecked(false);
					}
				}
				return permissions;
			}
		}
		return null;
	}

	@Override
	public List<Permissions> getPermissionTreeAsyc(String pid) {
		return null;
	}

	@Override
	public List<Permissions> getPermissionByIds(String ids) {
		List<Permissions> permissions = new ArrayList<Permissions>();
		if(null!=ids){
			permissions = permissionDao.findByIds(ids);
		}
		return permissions;
	}

	@Override
	public void update(Permissions p) {
		baseDao.update(p);
	}

}
